package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Permission;
import cn.wolfcode.query.JsonResult;
import cn.wolfcode.query.PageResult;
import cn.wolfcode.query.QueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.RequiredPermission;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
@RequestMapping("/permission")
public class PermissionController {

    @Autowired
    private IPermissionService permissionService;


    @RequiresPermissions(value = {"permission:list","权限列表"},logical = Logical.OR)
    //@RequiredPermission(name = "权限列表",expression = "permission:list")
    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") QueryObject qo) {
        //分页查询
        PageInfo<Permission> pageInfo = permissionService.query(qo);
        model.addAttribute("pageInfo", pageInfo);
        return "permission/list";
    }

    @RequestMapping("/input")
    public String input(Model model, Long id) {
        //判断id是否为空
        if (id != null) {
            //不为空则表示是编辑操作
            Permission permission = permissionService.get(id);
            model.addAttribute("permission", permission);
        }
        return "permission/input";
    }

    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Permission permission) {
        //判断id是否为空
        if (permission.getId() != null) {
            //不为空则表示是更改操作
            permissionService.update(permission);
        }else{
            //为空表示新增操作
            permissionService.save(permission);
        }
        return "redirect:/permission/list.do";
    }

    @RequestMapping("/delete")
    public String delete(Long id){
        //判断id是否为空
        if (id != null) {
            permissionService.delete(id);
        }
        return "redirect:/permission/list.do";
    }

    @RequestMapping("/reload")
    @ResponseBody
    public JsonResult reload(){
        try {
            permissionService.reload();
            return new JsonResult();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new JsonResult(false,"加载失败");

    }



}
